package com.mvvm.lib.base

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.impl.LoadingPopupView
import com.mvvm.lib.R
import java.lang.reflect.ParameterizedType

abstract class BaseVMFragment<VM : BaseViewModel, VB : ViewBinding> : BaseFragment<VB>() {

    protected lateinit var viewModel: VM


    //是否第一次加载
    private var isFirst: Boolean = true

    // private var dialog: MaterialDialog? = null
    protected open var loadingPop: LoadingPopupView? = null

    protected open val userDialog = false


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        createViewModel()
        if (userDialog) {
            createLoadView()
        }
        lifecycle.addObserver(viewModel)
        //注册 UI事件
        registerDefUIChange()
        super.onViewCreated(view, savedInstanceState)
    }


    override fun onResume() {
        super.onResume()
        onVisible()
    }

    /**
     * 使用 DataBinding时,要重写此方法返回相应的布局 id
     * 使用ViewBinding时，不用重写此方法
     */
    open fun layoutId(): Int = 0

    /**
     * 是否需要懒加载
     */
    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            lazyLoadData()
            isFirst = false
        }
    }

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        viewModel.defUI.showDialog.observe(viewLifecycleOwner) {
            showLoading()

        }
        viewModel.defUI.dismissDialog.observe(viewLifecycleOwner) {
            dismissLoading()
        }
        viewModel.defUI.toastEvent.observe(viewLifecycleOwner) {
            ToastUtils.showShort(it)
        }
        viewModel.defUI.msgEvent.observe(viewLifecycleOwner) {
            handleEvent(it)
        }
    }


    //创建加载框
    open fun createLoadView(maxWidth: Int = 220) {
        loadingPop = XPopup.Builder(requireActivity())
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .isViewMode(true)
            .hasShadowBg(false)
            //.maxWidth(maxWidth)
            //.maxWidth(maxWidth)
            // .popupWidth(SizeUtils.dp2px(maxWidth))
            //  .popupHeight(SizeUtils.dp2px(maxWidth) - 30)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .isLightNavigationBar(true)
            .asLoading("请求中...", R.layout.loading_view,LoadingPopupView.Style.Spinner)
    }


    override fun showLoading(info: String?) {
        if (userDialog) {
            loadingPop?.let {
                it.setTitle(info)
                if (!it.isShow) {
                    it.show()
                }
            }
        } else {
            super.showLoading(info)
        }

    }


    override fun dismissLoading() {
        super.dismissLoading()
        loadingPop?.dismiss()
    }

    /**
     * 创建 ViewModel
     *
     * 共享 ViewModel的时候，重写  Fragment 的 getViewModelStore() 方法，
     * 返回 activity 的  ViewModelStore 或者 父 Fragment 的 ViewModelStore
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[0]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            viewModel = ViewModelProvider(this)[tClass] as VM
        }
    }
}